package com.yxc.easyexceldemo.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.yxc.easyexceldemo.exception.DateTimeFormatException;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * @author: YXC
 * @time: 2022/11/15 15:20
 **/
public class LocalDateConvert implements Converter<LocalDate> {

    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    public Class<?> supportJavaTypeKey() {
        return LocalDate.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDate convertToJavaData(ReadConverterContext<?> context) throws Exception {
        String dateStr = context.getReadCellData().getStringValue();
        LocalDate date;
        try {
            date = LocalDate.parse(dateStr, df);
        } catch (DateTimeParseException e) {
            throw new DateTimeFormatException(dateStr, df.toString());
        }
        return date;
    }

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<LocalDate> context) throws Exception {
        LocalDate value = context.getValue();
        return new WriteCellData<>(df.format(value));
    }
}
